<template>
  <div class="app">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />

  </div>
</template>

<script>
import { reqImportBatch } from '@/api/employees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async  handleSuccess({ results, header }) {
      if (this.type === 'user') {
        this.handleEmployee(results, header)
      }
    //   this.tableData = results
    //   this.tableHeader = header
    },
    async handleEmployee(results, header) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const userInfo = {}
        for (const key in item) {
          if (['timeOfEntery', 'correctionTime'].includes[userRelations[key]]) {
            userInfo[userRelations[key]] = this.formatExcelDate(item[key], '-')
          } else {
            userInfo[userRelations[key]] = item[key]
          }
        }
        arr.push(userInfo)
      })
      const res = await reqImportBatch(arr)
      console.log(res)

      console.log(results, header)
      this.$message.success('导入成功，跳转回去')
      this.$router.push('/employees')
    },
    formatExcelDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }

}
</script>

<style>

</style>
